from apps.tax_policy.tax_policy.items import NetTaxPolicyItem
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import make_item
from utils.tools import urlencode, urldecode, parse_url_params


class HenanLyskxjsj124APolicy(BaseTaxPolicySpider):
    name = "henan_lyskxjsj_124a_policy"
    province: str = "河南省"  # 取表格
    city: str = "洛阳市"  # 取表格
    county: str = ""  # 取表格
    park: str = ""  # 取表格
    source: str = "洛阳市科学技术局"  # 取表格 同一个来源合并
    url: str = "https://kxjs.ly.gov.cn/#/luoyangCity?name=%E6%B4%9B%E9%98%B3%E5%B8%82&classifyId=28&j=0&k=0&typeId=5"  # 注明入口网址，以便后续排错
    auto_next: bool = True

    def start_requests(self):
        for i in range(1, 5):
            url = f"https://kxjs.ly.gov.cn/api/webInformation/getWebInformationClassify?page=1&size=4&classifyId=28&typeId={i}"
            yield self.Request(url, callback=self.parse_page)

    def parse_page(self, response, **kwargs):
        yield from self.parse_list(response, **kwargs)
        page_num = response.json()['data']['pages']
        for i in range(1, page_num + 1):
            root_url, params = parse_url_params(response.request.url)
            params["page"] = i
            new_url = root_url + "?" + urlencode(params)
            yield self.Request(new_url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        for i in response.json()['data']['records']:
            url = f"https://kxjs.ly.gov.cn/api/webInformation/getWebInformation?id={i['id']}"
            yield self.Request(url, callback=self.parse_content, cb_kwargs={
                "title": i["title"],
                "publish_time": i["addTime"],
            })

    def parse_content(self, response, **kwargs):
        title = kwargs.get("title")
        publish_date = kwargs.get("publish_time")
        content = response.json()['data']['content']

        item = dict(
            title=title,
            publish_date=publish_date,
            content=content,
            source_url=response.url,
            source=self.source,
            province=self.province,
            city=self.city,
            county=self.county,
            park=self.park,
        )
        if item["publish_date"]:
            yield make_item(NetTaxPolicyItem, item)


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_lyskxjsj_124a_policy".split())
